package com.study.lession.util.web;

import javax.servlet.http.HttpServletRequest;

import com.study.lession.util.StringUtil;

public class IpUtil {

    static String[] IPADDR_HEADERS = new String[] { "X-Requested-For", "X-Forwarded-For", "Proxy-Client-IP",
            "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "X-Real-IP", };

    /**
     * 竭力获取客户端真实ip
     * 
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = "";
        for (String header : IPADDR_HEADERS) {
            ip = request.getHeader(header);
            if (!StringUtil.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
